﻿using Beway.ValueAdded.Service;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Xml;
using Recharge = Beway.ValueAdded.Model.Recharge;

namespace Beway.ValueAdded.RechargeGateway.Controllers
{
    public class NotifyController : Controller
    {
        private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        RechargeServ rs = new RechargeServ();
        ReUserServ res = new ReUserServ();
        /// <summary>
        /// 黑龙江移动流量包充值确认接口
        /// </summary>
        /// <returns></returns>
        [ValidateInput(false)]
        public ActionResult ChinaMobile(string xmlhead, string xmlbody)
        {
            //string xmlhead, string xmlbody

            string result = "";
            Recharge recharge = new Recharge();
            log.Info(xmlhead + "\r\n************************\r\n" + xmlbody + "\r\n=====================\r\n");

            if (xmlhead != "" && xmlbody != "")//成功,
            {

                XmlDocument xmlBody = new XmlDocument();
                xmlBody.LoadXml(xmlbody);

                //获取CDATA区XML内容
                string svcCon = xmlBody.SelectSingleNode("InterBOSS/SvcCont").InnerText;
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(svcCon);
                //获取成功手机号数量
                string sucNum = doc.SelectSingleNode("AdditionResult/SuccNum").InnerText;
                //获取失败手机号数量
                string failNum = doc.SelectSingleNode("AdditionResult/FailNum").InnerText;

                //获取流水号
                string opSeq = doc.SelectSingleNode("AdditionResult/OperSeq").InnerText;

                XmlElement element;
                XmlElement element1;
                XmlElement element2;

                //成功
                int sNum = Convert.ToInt32(sucNum);
                if (sNum > 0)
                {                //获取成功的手机号的节点集合
                    XmlNodeList nodeListSuc = doc.GetElementsByTagName("SuccTel");
                    for (int i = 0; i < nodeListSuc.Count; i++)
                    {
                        element = (XmlElement)nodeListSuc.Item(i);
                        recharge.RCTarget = element.ChildNodes[0].Value;
                        //recharge.PayStatus = 1;//充值成功
                        recharge.RechargeStatus = 1; //充值成功
                        recharge.BatchOrderNo = opSeq;
                        recharge.RechargeSuccessTime = System.DateTime.Now;
                        recharge.RechargeErrorReason = "";
                        //改变充值状态
                        rs.UpdateByBatchNoAndRCTarget(recharge);

                    }
                }
                //失败
                int fNum = Convert.ToInt32(failNum);
                if (fNum > 0)
                {                //获取失败的手机号的节点集合
                    XmlNodeList nodeListFail = doc.GetElementsByTagName("MobNum");
                    //获取失败原因集合
                    XmlNodeList nodeListDesc = doc.GetElementsByTagName("RspDesc");
                    //获取失败代码
                    XmlNodeList nodeListCode = doc.GetElementsByTagName("Rsp");
                    for (int i = 0; i < nodeListFail.Count; i++)
                    {
                        element = (XmlElement)nodeListFail.Item(i);
                        element1 = (XmlElement)nodeListDesc.Item(i);
                        element2 = (XmlElement)nodeListCode.Item(i);
                        recharge.RCTarget = element.ChildNodes[0].Value;
                        //recharge.PayStatus = -9;//充值失败
                        recharge.RechargeStatus = -9;//充值失败
                        recharge.BatchOrderNo = opSeq;
                        recharge.RechargeSuccessTime = System.DateTime.Now;
                        recharge.RechargeErrorReason = element1.ChildNodes[0].Value + "--错误代码:" + element2.ChildNodes[0].Value;
                        //改变充值状态
                        rs.UpdateByBatchNoAndRCTarget(recharge);
                    }
                }

                //记录到日志
                StringBuilder sb = new StringBuilder();
                sb.Append("****************************\r\n");
                sb.Append("时间：" + System.DateTime.Now.ToString() + "\r\n");
                sb.Append("流水号：" + opSeq + "\r\n");
                sb.Append("成功数:" + sucNum + "\r\n");
                sb.Append("失败数:" + failNum + "\r\n");
                log.Error("黑龙江移动充值记录：" + sb.ToString());

                result = MessageHeadXml(xmlhead);
            }

            #region 废弃测试代码
            //string url = "https://testsite";
            //HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            //WebHeaderCollection whc = new WebHeaderCollection();
            //whc.Add("Authorization", "WSSE realm=\"DOMS\", profile=\"UsernameToken\", type=\"AppKey\"");
            //req.Headers = whc;
            //NetworkCredential nc = new NetworkCredential("username", "password");
            //req.Credentials = nc;
            #endregion
            return Content(result);
        }

        private string MessageHeadXml(string xmlhead)
        {
            XmlDocument xmlHead = new XmlDocument();
            xmlHead.LoadXml(xmlhead);
            string sessionID = xmlHead.SelectSingleNode("//TransInfo/SessionID").InnerText;
            string transIDO = xmlHead.SelectSingleNode("//TransInfo/TransIDO").InnerText;
            string transIDOTime = xmlHead.SelectSingleNode("//TransInfo/TransIDOTime").InnerText;
            DateTime dt = DateTime.Now;
            string bipCode = "BIP4B877";
            string actCode = "T4011138";
            string seq = dt.ToString("yyMMddHHmmss");
            string orderSeqID = "BWHD" + dt.ToString("yyyyMMddHHmmss") + seq;
            string transIDH = orderSeqID;
            string transIDHTime = dt.ToString("yyyyMMddHHmmss");
            string msgHead = "<?xml version='1.0' encoding='UTF-8'?>" +
                            "<InterBOSS>" +
                            "<Version>0100</Version>" +
                            "<TestFlag>0</TestFlag>" +
                            "<BIPType>" +
                            "<BIPCode>" + bipCode + "</BIPCode>" +
                            "<ActivityCode>" + actCode + "</ActivityCode>" +
                            "<ActionCode>1</ActionCode>" +
                            "</BIPType>" +
                            "<RoutingInfo>" +
                            "<OrigDomain>STKP</OrigDomain>" +
                            "<RouteType>00</RouteType>" +
                            "<Routing>" +
                            "<HomeDomain>BBOSS</HomeDomain>" +
                            "<RouteValue>998</RouteValue>" +
                            "</Routing>" +
                            "</RoutingInfo>" +
                            "<TransInfo>" +
                            "<SessionID>" + sessionID + "</SessionID>" +
                            "<TransIDO>" + transIDO + "</TransIDO>" +
                            "<TransIDOTime>" + transIDOTime + "</TransIDOTime>" +
                            "<TransIDH>" + transIDH + "</TransIDH>" +
                            "<TransIDHTime>" + transIDHTime + "</TransIDHTime>" +
                            "</TransInfo>" +
                             "<Response>" +
                             "<RspType>0</RspType>" +
                             "<RspCode>0000</RspCode>" +
                             "<RspDesc>success</RspDesc>" +
                             "</Response>" +
                            "</InterBOSS>";
            return msgHead;
        }
    }
}
